package com.rabbitmq.demo;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @ClassName Producer
 * @Description 系统发送消息（生产者）
 * @Author Kx
 * @Date 2025/10/10 19:27
 * @Version 1.0
 */
public class Producer {
    /**
     * 定义交换机的名称
    */
    private static final String EXCHANGE_NAME = "channel.direct";

    /**
     * 定义连接工厂
     */
    private static ConnectionFactory connectionFactory;

    /**
     * 初始化工厂
    */
    static {
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("kx");
        connectionFactory.setPassword("123456");
    }

    /**
     * @author: kx
     * @date: 2025/10/10 19:42
     * @param message : 消息内容
     * @param key : 绑定键
     * @description: 发送消息
    */
    public static void send(String message, String key) {
        // 创建连接和通信
        try (Connection connection = connectionFactory.newConnection();
             Channel channel = connection.createChannel()){

            // 创建交换机并指定类型
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            // 发送信息给交换机
            channel.basicPublish(EXCHANGE_NAME, key, null, message.getBytes());
        } catch (Exception e) {
            throw new RuntimeException("投递失败" + e);
        }
    }

    public static void main(String[] args) {
        send("体育", "sports.key");
        send("新闻", "journalism.key");
    }
}
